import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:juming_test/model/home/home_kingkong_model.dart';
import 'package:juming_test/model/home/kingkong_management_section_model.dart';
import 'package:juming_test/view_models/home/home_kingkong_view_model.dart';
import 'package:logger/logger.dart';

class HomeKingkongManagementLogic extends GetxController {
  // 金刚位ViewModel
  final HomeKingkongViewModel homeKingkongViewModel = Get.put(
    HomeKingkongViewModel(),
  );

  // 是否编辑状态
  final Rx<bool> isEditing = false.obs;

  // 网格key
  final gridViewKey = GlobalKey();

  final Logger _logger = Logger();

  @override
  Future<void> onReady() async {
    super.onReady();
    homeKingkongViewModel.getAllKingkongList();
  }

  @override
  void onClose() {
    _logger.d('KingkongManagementLogic onClose');
    super.onClose();
  }

  // 进入编辑模式
  void enterEdit() {
    homeKingkongViewModel.editSections.value =
        homeKingkongViewModel.normalSections.value
            .map(
              (section) =>
                  KingkongManagementSectionModel.fromJson(section.toJson()),
            )
            .toList();
    isEditing.value = true;
  }

  // 取消编辑
  void cancelEdit() {
    isEditing.value = false;
  }

  // 确认编辑
  void confirmEdit() {
    homeKingkongViewModel.normalSections.value =
        homeKingkongViewModel.editSections.value
            .map(
              (section) =>
                  KingkongManagementSectionModel.fromJson(section.toJson()),
            )
            .toList();
    isEditing.value = false;
    // 保存数据到本地
    final items = homeKingkongViewModel.normalSections.value.first.items;
    homeKingkongViewModel.cacheKingkongList(items);
  }

  // 恢复默认设置
  void resetToDefault() async {
    List<HomeKingkongModel> items = homeKingkongViewModel.getDefaultItems();
    homeKingkongViewModel.editSections.value = homeKingkongViewModel
        .getSectionsByItems(items);
    homeKingkongViewModel.normalSections.value = homeKingkongViewModel
        .getSectionsByItems(items);
    // 配置缓存到本地
    homeKingkongViewModel.cacheKingkongList(items);
  }

  // 拖拽排序
  void dragSort(List<HomeKingkongModel> sortList) {
    final editActiveSection = homeKingkongViewModel.editSections.value.first;
    editActiveSection.items =
        sortList
            .map((item) => HomeKingkongModel.fromJson(item.toJson()))
            .toList();
  }
}
